/*
 * @Author: liaoshuang 345324985@qq.com
 * @Date: 2023-12-21 11:53:22
 * @LastEditors: liaoshuang 345324985@qq.com
 * @LastEditTime: 2024-01-05 16:47:46
 * @FilePath: \h5-pda\src\http\index.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import axios from "axios";
import { Toast } from "vant";
let toast = null;
axios.defaults.headers.post["Content-Type"] = "application/json";
// 添加请求拦截器
axios.interceptors.request.use(
  function (config) {
    toast = Toast.loading({
      duration: 0,
      message: "Loading...",
      forbidClick: true,
    });
    let token = sessionStorage.getItem("token");
    let userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
    let currentDepartment = JSON.parse(
      sessionStorage.getItem("currentDepartment")
    )?.name;
    if (token) token = JSON.parse(token);
    else token = null;
    let currentFacility = localStorage.getItem("currentFacility");

    let currentLanguage = localStorage.getItem("lang") || "en";
    // 在发送请求之前做些什么
    if (config.method === "post") {
      config.data = {
        currentLanguage,
        currentFacility,
        token: userInfo,
        currentDepartment,
        ...config.data,
      };
    } else if (config.method === "get") {
      config.params = {
        currentLanguage,
        currentFacility,
        token: userInfo,
        currentDepartment,
        ...config.params,
      };
    }
    return config;
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
axios.interceptors.response.use(
  function (response) {
    toast.clear();
    // 对响应数据做点什么
    if (response.status === 200 && response.data.code === 200) {
      return response.data.result;
    } else {
      Toast(response.data.message || response.statusText);
      return Promise.reject(response.data);
    }
  },
  function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);
